package com.javatest.springbootcache01.service;

import com.javatest.springbootcache01.bean.Department;
import com.javatest.springbootcache01.mapper.DepartmentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.Cache;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.stereotype.Service;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2019/3/24 11:13
 */
@Service
public class DeptService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Qualifier("deptCacheManager")
    @Autowired
    private RedisCacheManager deptCacheManager;

    /**
     * 缓存的数据能存入redis
     * 第二次从缓存中查询，就不能反序列化回来：
     * 原因是存的是dept的json数据，CacheManager默认使用RedisTemplate<Object, Employee>操作Redis
     *
     * @param id
     * @return
     */
    /*@Cacheable(value = "dept",cacheManager = "deptCacheManager")
    public Department getDeptById(Integer id){
        System.out.println("查询部门:" + id);
        Department department = departmentMapper.getDeptById(id);
        return department;
    }*/


    // 使用缓存管理器得到缓存，进行api调用
    public Department getDeptById(Integer id) {
        System.out.println("查询部门:" + id);
        Department department = departmentMapper.getDeptById(id);

        // 获取某个缓存
        final Cache dept = deptCacheManager.getCache("dept");
        dept.put("dept:" + id, department);

        return department;
    }
}
